package cn.dgut.training.controller;


import cn.dgut.training.annotation.LoginUser;
import cn.dgut.training.e.Status;
import cn.dgut.training.entity.user.Balance;
import cn.dgut.training.service.impl.BalanceServiceImpl;
import cn.dgut.training.vo.CommonResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;

@RestController
@RequestMapping("/balance")
public class BalanceController {

    @Autowired
    private BalanceServiceImpl balanceService;

    @GetMapping("/select")
    public CommonResponse select(@LoginUser Long userId) {
        BigDecimal money = balanceService.getOne(new QueryWrapper<Balance>().lambda().eq(Balance::getUserId, userId)).getMoney();
        return CommonResponse.success(money);
    }

    @PostMapping("/update")
    public CommonResponse update(@LoginUser Long userId, @RequestParam("price") String price) {
        BigDecimal price1 = new BigDecimal(price);
        Balance balance = balanceService.getOne(new QueryWrapper<Balance>().lambda().eq(Balance::getUserId, userId));
        if (balance.getMoney().compareTo(price1.multiply(new BigDecimal(-1))) < 0) {
            return CommonResponse.fail(Status.PAY_ERROR.getCode(), Status.PAY_ERROR.getMessage() + ":余额不足");
        } else {
            BigDecimal money = balance.getMoney().add(price1);
            balance.setMoney(money);
            balanceService.updateById(balance);
        }
        return CommonResponse.message();
    }


    @GetMapping("/create")
    public CommonResponse create(@RequestParam("userId") Long userId) {
        balanceService.createBalance(userId);
        return CommonResponse.message();
    }

    @PostMapping("/iDeletion")
    public void iDeletion(@RequestParam("userId") Long userId, @RequestParam("price") String price) {
        BigDecimal money = new BigDecimal(price);
        Balance balance = balanceService.getOne(new QueryWrapper<Balance>().lambda().eq(Balance::getUserId, userId));
        BigDecimal money1 = balance.getMoney().add(money);
        balance.setMoney(money1);
        balanceService.updateById(balance);
    }
}
